package com.jingbit.ai.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class AssetsUtil {

    public static void mergeFile(Context ctx,String srcDir,String dstPath){
        AssetManager assetManager = ctx.getAssets();
        try {
            String[] data = assetManager.list(srcDir);
            mergeFile(ctx, data, dstPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void mergeFile(Context c, String[] partFileList, String dst) throws IOException {
        if (!new File(dst).exists()) {
            OutputStream out = new FileOutputStream(dst);
            byte[] buffer = new byte[1024];
            InputStream in;
            int readLen = 0;
            for(int i=0;i<partFileList.length;i++){
                // 获得输入流 ,注意文件的路径
                in = c.getAssets().open(partFileList[i]);
                while((readLen = in.read(buffer)) != -1){
                    out.write(buffer, 0, readLen);
                }
                out.flush();
                in.close();
            }
            // 把所有小文件都进行写操作后才关闭输出流，这样就会合并为一个文件了
            out.close();
        }
    }
    
    public static Bitmap getBitmap(Context ctx,String name){
        AssetManager asm=ctx.getAssets();
        InputStream inputStream=null;
        try{
            inputStream=asm.open(name);
        }catch(IOException e){
            e.printStackTrace();
        }
        Drawable d= Drawable.createFromStream(inputStream,null);
        Bitmap b=((BitmapDrawable)d).getBitmap();
        return b;
    }
}